package com.tingyuge.thinking.spring.configuration.bean.lifecycle;

import com.tingyuge.thinking.spring.ioc.overview.domain.SuperUser;
import com.tingyuge.thinking.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor;

/**
 * bean 实例化 生命周期实例
 * 这里添加beanPostProcessor
 * org.springframework.context.support.AbstractApplicationContext#registerBeanPostProcessors()
 * 这里注意: 如果你的配置文件加了注解扫描,会触发applicationContext.registerBeanPostProcessor 的一些内建的 beanPost 导致调用出错
 * @author xiaodao
 * @version 1.0
 * @date 2021/7/10
 */
public class BeanInitializationLifecycleDemo {
    public static void main(String[] args) {
        executeBeanFactory();

    }

    public static void executeBeanFactory() {
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        //bean的注册,只能在applicationContext中注册.
        //方法1: 添加 beanPostProcessor 实例 MyInstantiationAwareBeanPostProcessor
        beanFactory.addBeanPostProcessor(new MyInstantiationAwareBeanPostProcessor());
        //添加 CommonAnnotationBeanPostProcessor 解决@postConstruct
        beanFactory.addBeanPostProcessor(new CommonAnnotationBeanPostProcessor());
        //基于 XML 资源 BeanDefinitionReader
        XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
        String[] locations = {"/META-INF/dependency-lookup-context.xml", "/META-INF/bean-dependency-construct-injection.xml"};
        //指定字符编码
        int beanNumbers = xmlBeanDefinitionReader.loadBeanDefinitions(locations);
        System.out.println("已加载: BeanDefinition的数量: " + beanNumbers);

        // SmartInitializingSingletonBean
        // 将已注册的 BeanDefinition 初始化为 spring Bean()
        beanFactory.preInstantiateSingletons();
        SuperUser supperUser = beanFactory.getBean("superUser", SuperUser.class);
        System.out.println(supperUser);
        User user = beanFactory.getBean("user", User.class);
        System.out.println(user);
        //按照类型的方式进行注入  resolveDependency
        UserHolder userHolder = beanFactory.getBean("userHolder", UserHolder.class);
        System.out.println(userHolder);
    }


}
